package filter;

import Model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: wsn_blog
 * @description
 * @author:王松年
 * @creat: 2021-07-12 22:56:35
 **/
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //用于处理http的请求和响应
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse) response;
        //获取请求的服务路径：
        String uri = req.getServletPath();
        if (!uri.startsWith("/js/")&&!uri.startsWith("/public/")&&!uri.equals("/register")&&!uri.equals("/login")){
            HttpSession session = req.getSession(false);
            if (session != null){
                User user = (User)session.getAttribute("user");
                if (user!=null){
                    chain.doFilter(request,response);
                    return;
                }
            }
            //只要未登录，统一跳转至首页
            //获取协议
            String schema = req.getScheme();
            //获取IP地址
            String host = req.getServerName();
            //获取端口号
            int port = req.getServerPort();
            //获取应用上下文路径
            String contextPath = req.getContextPath();
            String basePath = schema + "://" + host + ":" + port + contextPath;
            resp.sendRedirect(basePath + "/public/home.html");

        }else{
            chain.doFilter(request,response);
        }

    }
    @Override
    public void destroy() {

    }
}
